package controller

import (
	"ginfast/api/system/dto"
	"ginfast/api/system/model"
	"ginfast/api/system/service"
	"ginfast/middleware"
	"ginfast/pkg/ctx"
	"ginfast/pkg/orm"
	"ginfast/util"

	"github.com/gin-gonic/gin"
)

// Menu 系统管理菜单
type Menu struct {
}

// ListHandler 菜单列表
func (Menu) ListHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	var data []model.Menu
	p.DbModelWhere(&model.Menu{}).Find(&data)
	ctx.JSONWriteData(data, c)
}

// TreeSelectHandler 列表
func (Menu) TreeSelectHandler(c *gin.Context) {
	data := service.MenuTree(middleware.GetUser(c).RoleID)
	ctx.JSONWriteData(data, c)
}

// RoleMenuTreeHandler 角色菜单列表
func (Menu) RoleMenuTreeHandler(c *gin.Context) {
	id := ctx.ParamUInt(c, "id")
	data := service.MenuTree(id)
	ctx.JSONWriteData(gin.H{"menus": data}, c)
}

// GetHandler 查询菜单详细
func (Menu) GetHandler(c *gin.Context) {
	util.QueryByID(&model.Menu{}, c)
}

// AddHandler 新增
func (Menu) AddHandler(c *gin.Context) {
	var p model.Menu
	if err := c.ShouldBind(&p.MenuOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbCreate(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// UpdateHandler 修改
func (Menu) UpdateHandler(c *gin.Context) {
	var p model.Menu
	if err := c.ShouldBind(&p.MenuOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbUpdateModel(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// DeleteHandler 删除菜单
func (Menu) DeleteHandler(c *gin.Context) {
	util.Deletes(&model.Menu{}, c)
}

func (o Menu) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/:id", o.GetHandler)
	r.GET("/treeselect", o.TreeSelectHandler)
	r.GET("/roleMenuTreeselect/:id", o.RoleMenuTreeHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.DELETE("/:id", o.DeleteHandler)
}
